import { JwtAuthGuard } from './../auth/jwt-auth.guard';
import { AdminUser } from './admin-user.entity';
import { AdminUserService } from './admin-user.service';
import { AdminuserParam } from './admin-user.param';
import { Resolver, Query, Args, Context } from '@nestjs/graphql';
import { AuthService } from '../auth/auth.service';
import { InternalServerErrorException, UseGuards } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { RedisService } from '../util/redis.service';
import { ConfigProvider } from 'src/config/config.provider';

@Resolver(of => AdminUser)
export class AdminUserResolver {

  constructor(private service: AdminUserService,
              private authService: AuthService,
              private redisService: RedisService) {}

  @Query(returns => String)
  async login(@Args('loginParam') loginParam: AdminuserParam, @Context() context) {
    const user = await this.service.getOne({
      login: loginParam.userName,
    });
    if (!user || user.length < 1) {
      throw new InternalServerErrorException('登录失败，账户或者密码错误');
    }
    const checked = bcrypt.compareSync(loginParam.password, user[0].password);
    if (checked) {
      const token = await this.authService.signIn({
        userName: loginParam.userName,
        id: user[0].id,
      });
      context.res.cookie('secret_token', token, { maxAge: 1000 * 60 * 60 * 24 * 7 });
      return '登录成功';
    } else {
      throw new InternalServerErrorException('登录失败，账户或者密码错误');
    }
  }

  @Query(returns => AdminUser, { name: 'loginInfo' })
  @UseGuards(JwtAuthGuard)
  getInfo(@Context() context): AdminUser {
    return context.req.user.user;
  }

  @UseGuards(JwtAuthGuard)
  @Query(returns => String)
  logout(@Context() context) {
    // 清除cookie
    context.res.clearCookie('secret_token');
    // 清除redis保存的权限
    const key = `${ConfigProvider.getConfig('constant').userPrivKey + context.req.user.user.id}`;
    console.log('key is ', key);
    this.redisService.del(key);
    return '登出成功!';
  }

}
